// src/utils/http.js
import { useAuthStore } from '@/stores/auth'

const API_BASE_URL = process.env.VUE_APP_API_BASE_URL || 'http://localhost:8000'

// 创建带认证的fetch函数
export const authenticatedFetch = async (url, options = {}) => {
  const authStore = useAuthStore()
  
  // 检查token是否过期，如果过期则尝试刷新
  if (authStore.isTokenExpired && authStore.refreshToken) {
    try {
      await authStore.refreshAccessToken()
    } catch (error) {
      // 刷新失败，跳转到登录页
      window.location.href = '/login'
      return
    }
  }
  
  // 添加认证头
  const headers = {
    'Content-Type': 'application/json',
    ...options.headers
  }
  
  if (authStore.accessToken) {
    headers.Authorization = `Bearer ${authStore.accessToken}`
  }
  
  const config = {
    ...options,
    headers
  }
  
  const response = await fetch(`${API_BASE_URL}${url}`, config)
  
  // 如果返回401，尝试刷新token
  if (response.status === 401 && authStore.refreshToken) {
    try {
      await authStore.refreshAccessToken()
      // 重新发起请求
      headers.Authorization = `Bearer ${authStore.accessToken}`
      return await fetch(`${API_BASE_URL}${url}`, { ...config, headers })
    } catch (error) {
      authStore.clearAuth()
      window.location.href = '/login'
      throw error
    }
  }
  
  return response
}